package gpt

// pkg/gpt/word_search.go
import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"

	"github.com/sony/gobreaker"
)

const (
	GPT_VERSION_THREE = "gpt-3.5-turbo"
	GPT_VERSION_FOUR  = "gpt-4-0125-preview"
)

var circuitBreaker *gobreaker.CircuitBreaker

func init() {
	circuitBreaker = gobreaker.NewCircuitBreaker(gobreaker.Settings{
		Name:    "GPT_API",
		Timeout: 10 * time.Second,
		ReadyToTrip: func(counts gobreaker.Counts) bool {
			return counts.ConsecutiveFailures > 5
		},
	})
}

// WordSearch 封装 GPT 请求
type WordSearch struct {
	Keyword string
	Model   string
}

// NewWordSearch 创建 WordSearch 实例
func NewWordSearch(keyword, model string) *WordSearch {
	return &WordSearch{
		Keyword: keyword,
		Model:   model,
	}
}

// SearchWordFromGpt 向 GPT 发送请求
func (ws *WordSearch) SearchWordFromGpt() (map[string]interface{}, error) {
	var url string
	if ws.Model == GPT_VERSION_THREE {
		url = fmt.Sprintf("http://gpt.fengyin.tv/portal/search/ChatGptApi3?keyword=%s", ws.Keyword)
	} else {
		url = fmt.Sprintf("http://gpt.fengyin.tv/portal/search/ChatGptApi?keyword=%s", ws.Keyword)
	}

	client := &http.Client{Timeout: 10 * time.Second}
	resp, err := client.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("failed to fetch data from GPT: status code %d", resp.StatusCode)
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	var result map[string]interface{}
	err = json.Unmarshal(body, &result)
	if err != nil {
		return nil, err
	}

	return result["data"].(map[string]interface{}), nil
}

// DouBao 调用另一个 API 获取数据
func (ws *WordSearch) DouBao() (map[string]interface{}, error) {
	url := "https://ark.cn-beijing.volces.com/api/v3/chat/completions"
	model := "ep-20250109182938-pgcgv"

	message := []map[string]interface{}{
		{
			"role":    "user",
			"content": ws.Keyword,
		},
	}

	payload := map[string]interface{}{
		"model":    model,
		"messages": message,
	}

	payloadBytes, err := json.Marshal(payload)
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest("POST", url, strings.NewReader(string(payloadBytes)))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Authorization", "Bearer aba49aea-b00c-4a23-b0b0-8ce7951a6eff")
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 30 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusMultipleChoices {
		var result map[string]interface{}
		err := json.NewDecoder(resp.Body).Decode(&result)
		if err != nil {
			return nil, err
		}
		choices := result["choices"].([]interface{})
		content := choices[0].(map[string]interface{})["message"].(map[string]interface{})["content"].(string)
		content = strings.ReplaceAll(content, "\r", "")
		content = strings.ReplaceAll(content, "\n", "")
		content = strings.ReplaceAll(content, " ", "")

		if content != "" {
			var data map[string]interface{}
			err := json.Unmarshal([]byte(content), &data)
			if err != nil {
				return nil, err
			}
			if hashtags, ok := data["hashtag"].([]interface{}); ok {
				for i, tag := range hashtags {
					hashtags[i] = "#" + tag.(string)
				}
				data["hashtag"] = hashtags
			}
			return data, nil
		}
	}
	return nil, fmt.Errorf("请求失败，状态码: %d", resp.StatusCode)
}
